/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import org.aswing.geom.Dimension;

import com.bourre.core.HashCodeFactory;
import com.bourre.data.libs.GraphicLibEvent;
import com.bourre.events.BubbleEvent;
import com.bourre.events.EventType;
import com.bourre.events.IEvent;
import com.bourre.medias.video.VideoDisplayEvent;

import fever.app.local.Localisation;
import fever.app.local.LocalisationEvent;
import fever.app.local.LocalisationListener;
import fever.app.menu.FvContextMenu;
import fever.app.menu.FvContextMenuEvent;
import fever.app.menu.FvContextMenuItem;
import fever.events.ApplicationEvent;
import fever.events.StageEvent;
import fever.Fever;
import fever.medias.video.FvVideoDisplay;
import fever.medias.video.VideoCuePointEvent;
import fever.medias.video.VideoMetaData;

import fvaswing.components.alert.FvAlertType;
import fvaswing.components.FvAlert;
import fvaswing.components.reader.abstract.FvReaderDocument;
import fvaswing.components.reader.abstract.FvReaderEvent;
import fvaswing.components.reader.FvReaderResources;
import fvaswing.components.reader.FvVideoPlayer;
import fvaswing.components.reader.video.FvFullScreenPlayer;
import fvaswing.components.reader.video.FvVideoDocumentListener;
import fvaswing.components.reader.video.FvVideoItem;

/**
 * Video document manager.
 *
 * @author Romain Ecarnot
 */
class fvaswing.components.reader.video.FvVideoDocument extends FvReaderDocument
	implements LocalisationListener
{
	//-------------------------------------------------------------------------
	// Events definition
	//-------------------------------------------------------------------------
	
	/** Broadcasted when an error occured. */
	public static var onMetaDataEVENT : EventType = FvVideoDisplay.onMetaDataEVENT;
	
	/** Broadcasted when fullscreen player is enabled / disabled. */
	public static var onFullScreenEVENT : EventType = new EventType( "onFullScreen" );
	
	/** Broadcasted when user toggle "play/pause" property of current video. */
	public static var onVideoPlayChangeEVENT : EventType = new EventType( "onVideoPlayChange" );
	
	/** Broadcasted when user stop video. */
	public static var onVideoStopEVENT : EventType = new EventType( "onVideoStop" );
	
	/** Broadcasted when user change video volume ( not muting ). */
	public static var onVideoVolumeChangeEVENT : EventType = new EventType( "onVideoVolumeChange" );
	
	/** Broadcasted when user toggle "mute" property of current video. */
	public static var onVideoMuteEVENT : EventType = new EventType( "onVideoMute" );
	
	/** Broadcasted when user stop video. */
	public static var onVideoResizeEVENT : EventType = FvVideoDisplay.onResizeEVENT;
	
	 /** Broadcasted when user stop video. */
	public static var onVideoPlayHeadChangeEVENT : EventType = new EventType( "onVideoPlayHeadChange" );
	
	/** Broadcasted when stream starts playing. */
	public static var onStartStreamEVENT : EventType = FvVideoDisplay.onStartStreamEVENT;
	
	/** Broadcasted when stream is finished. */
	public static var onEndStreamEVENT : EventType = FvVideoDisplay.onEndStreamEVENT;
	
	/** Broadcasted when buffer is full. */
	public static var onBufferFullEVENT : EventType = FvVideoDisplay.onBufferFullEVENT;
	
	/** Broadcasted when buffer is empty. */
	public static var onBufferEmptyEVENT : EventType = FvVideoDisplay.onBufferEmptyEVENT;
	
	
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private var _resources : FvReaderResources;
	
	private var _videoMC : MovieClip;
	private var _controller : FvVideoDisplay;
	private var _holdVolume : Number;	private var _muteState : Boolean;
	private var _fullPlayer : FvFullScreenPlayer;
	private var _alertDialog : FvAlert;
	
	// context
	private var _contextMenu : FvContextMenu;
	private var _playItemContext : FvContextMenuItem;
	private var _stopItemContext : FvContextMenuItem;
	private var _fullItemContext : FvContextMenuItem;
	private var _incVolumeContext : FvContextMenuItem;
	private var _decVolumeContext : FvContextMenuItem;
	private var _muteVolumeContext : FvContextMenuItem;
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	public function FvVideoDocument( reader : FvVideoPlayer, target : MovieClip )
	{
		super( reader );
		
		_videoMC = target.attachMovie( "VideoDisplay", "__video" + HashCodeFactory.getKey( this ), 1 );
		
		_resources = FvReaderResources.getInstance();
		Localisation.addLocalisationListener( this );
		
		_createContextMenu();
		
		_muteState = false;
		
		_fullPlayer = new FvFullScreenPlayer();
		
		_alertDialog = new FvAlert( FvAlertType.OK_ONLY );
		_alertDialog.title = _resources.videoFullErrorTitle + " ( " + Fever.client.player.getVersion() + " )";
		_alertDialog.message = _resources.videoFullErrorMessage;
		_alertDialog.addListener( _onCloseAlertDialog, this );
		
		_controller = new FvVideoDisplay( _videoMC,  _videoMC['video'] );
		_controller.setAutoSize( false );
		_controller.setLoopPlayback( true );
		_controller.setAntiCache( false );
		_controller.addEventListener( FvVideoDisplay.onStartStreamEVENT, this, _onDocumentLoaded );		_controller.addEventListener( FvVideoDisplay.onErrorEVENT, this, _onDocumentError );		_controller.addEventListener( FvVideoDisplay.onTimeOutEVENT, this, _onDocumentError );		_controller.addEventListener( FvVideoDisplay.onPlayHeadTimeChangeEVENT, this, _onPlayHeadChange );		_controller.addEventListener( FvVideoDisplay.onCuePointEVENT, this, _onCuePoint );
		
		_controller.addEventListener( onEndStreamEVENT, this, _bubbleEvent );
		_controller.addEventListener( onBufferFullEVENT, this, _bubbleEvent );
		_controller.addEventListener( onBufferEmptyEVENT, this, _bubbleEvent );
	}
	
	/**
	 * Adds passed-in {@code listener} for receiving all document events.
	 * 
	 * @param listener Listener object
	 */
	public function addListener( listener : FvVideoDocumentListener ) : Void
	{
		super.addListener( listener );
	}
	
	/**
	 * Removes passed-in {@code listener} for receiving all document events.
	 * 
	 * @param listener Listener object
	 */
	public function removeListener( listener : FvVideoDocumentListener ) : Void
	{
		super.removeListener( listener );	
	}
	
	/**
	 * There is no loading progression for flv file.
	 */
	public function getPercent() : Number
	{
		return null;
	}
	
	/**
	 * Sets the display size of the document, in pixels.
	 */
	public function setSize( size : Dimension ) : Void
	{
		var videoSize : Dimension = getDocument().getSize();
		
		if( !videoSize )
			videoSize = new Dimension( _controller.getWidth(), _controller.getHeight() );	
		
        var scale : Number = Math.max( videoSize.width / size.width, videoSize.height / size.height );
        var newW : Number = videoSize.width / scale;        var newH : Number = videoSize.height / scale;
        
        _controller.setSize( newW, newH  );
        _controller.move( size.width / 2 - newW / 2, size.height / 2 - newH / 2 );
	}
	
	/**
	 * Returns current {@link fvaswing.components.reader.video.FvVideoItem}
	 */
	public function getDocument() : FvVideoItem
	{
		return FvVideoItem( _current );
	}
	
	/**
	 * Returns metadata for current video.
	 */
	public function getMetaData() : VideoMetaData
	{
		return _controller.getMetaData();	
	}
	
	/**
	 * Returns defined cue points in current video.
	 */
	public function getCuePoints() : Array
	{
		return _controller.getCuePoints();	
	}
	
	/**
	 * Plays video
	 * 
	 * @param n ( optional ) playhead time position
	 */
	public function play( n : Number ) : Void
	{
		_controller.play( n );
		_fireEventType( onVideoPlayChangeEVENT );
	}
	
	/**
	 * Pauses video.
	 */
	public function pause(  ) : Void
	{
		_controller.pause();
		_fireEventType( onVideoPlayChangeEVENT );
	}
	
	/**
	 * Toggles play/pause
	 */
	public function toggle() : Void
	{
		if( _controller.isPlaying() ) pause();
		else play();
	}
	
	/**
	 * Move video playhead to position {@code n}
	 * 
	 * <p>Checks {@link fvaswing.components.reader.video.FvVideoItem#isPHPStreaming()} 
	 * before seeking.
	 */
	public function seek( n : Number ) : Void
	{
		if( getDocument().isPHPStreaming() )
			_controller.streamFromPHP( n );
		else _controller.setPlayheadTime( n );
	}
	 
	/**
	 * Returns current playhead time.
	 */
	public function getPlayHeadTime() : Number
	{
		return _controller.getPlayheadTime();
	}
	
	/**
	 * Defines video volume value.
	 */
	public function setVolume( n : Number ) : Void
	{
		_controller.setVolume( n );
		_fireEventType( onVideoVolumeChangeEVENT );
	}
	
	/**
	 * Returns video volume.
	 */
	public function getVolume() : Number
	{
		return _controller.getVolume();	
	}
	
	/**
	 * Increases or descreases video volume by 
	 * passed-in {@code n} value.
	 * 
	 * <p>Checks if new value is in a valid range ( 0-100 ) before 
	 * sending value to the video controller.
	 */
	public function appendVolume( n : Number ) : Void
	{
		var v : Number = _controller.getVolume();
		v = v+ n;
		
		if( v > 100 ) v = 100;
		else if( v < 0 ) v = 0;
		
		setVolume( v );	
	}
	
	/**
	 * Toggles mute on/off state.
	 */
	public function mute() : Void
	{
		_muteState = !_muteState;
		
		if( _muteState )
		{
			_holdVolume = _controller.getVolume();
			_controller.setVolume( 0 );
		}
		else _controller.setVolume( _holdVolume );
		
		_fireEventType( onVideoMuteEVENT );
	}
	
	/**
	 * Returns {@code true} if volume is currently mute.
	 */
	public function isMute() : Boolean
	{
		return _muteState;	
	}
	
	/**
	 * Returns {@code true} if video is currently playing.
	 */
	public function isPlaying() : Boolean
	{
		return _controller.isPlaying();	
	}
	
	/**
	 * Stops current video
	 */
	public function stop() : Void
	{
		_controller.stop();
		_fireEventType( onVideoStopEVENT );
	}
	
 	/**
 	 * Releases document and all event listeners subscription.
 	 */
 	public function release() : Void
 	{
 		_controller.release();
 	}
 	
 	/**
 	 * Opens current video in Fullscreen mode.
 	 * 
 	 * <p>You player must be "FullScreen mode" compliant"<br />
 	 * Otherwise a {@link fvaswing.components.FvAlert} dialog open.
 	 */
 	public function openFullScreen() : Void
 	{
 		if( Fever.client.player.isFullScreenCompliant() )
		{
			Fever.application.addEventListener( ApplicationEvent.onStateChangeEVENT, this, _onModeChanged );
			pause();
			
			_fullPlayer.open( getDocument(), getPlayHeadTime() );
			_fireEventType( onFullScreenEVENT );
		}
		else
		{
			pause();
			_alertDialog.open();
		}	
 	}
 	
 	/**
 	 * Triggered when Localisation language change.
 	 */
 	public function onLocalisationUpdate( event : LocalisationEvent ) : Void
 	{
		_playItemContext.caption = _resources.videoPlay;
		_stopItemContext.caption = _resources.videoStop;
		_fullItemContext.caption = _resources.videoFull;
		_incVolumeContext.caption = _resources.videoIncrease;
		_decVolumeContext.caption = _resources.videoDecrease;
		_muteVolumeContext.caption = _resources.videoMute;
		
		_alertDialog.title = _resources.videoFullErrorTitle + " ( " + Fever.client.player.getVersion() + " )";
		_alertDialog.message = _resources.videoFullErrorMessage;
 	}
 	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private function _load( url : String ) : Void
	{
		_controller.addEventListener( FvVideoDisplay.onMetaDataEVENT, this, _onMetaData );
		_controller.load( url );
		
		_videoMC.menu = null;
	}
	
	private function _getReader() : FvVideoPlayer
	{
		return FvVideoPlayer( parent );
	}
	
	private function _createContextMenu() : Void
	{
		_fullItemContext = new FvContextMenuItem( _resources.videoFull );
		_fullItemContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, openFullScreen );
		
		_playItemContext = new FvContextMenuItem( _resources.videoPlay, true );
		_playItemContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, toggle );
		
		_stopItemContext = new FvContextMenuItem( _resources.videoStop );
		_stopItemContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, stop );
		
		_incVolumeContext = new FvContextMenuItem( _resources.videoIncrease, true );
		_incVolumeContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, _onContextAppendVolume, 10 );
		
		_decVolumeContext = new FvContextMenuItem( _resources.videoDecrease );
		_decVolumeContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, _onContextAppendVolume, -10 );
		
		_muteVolumeContext = new FvContextMenuItem( _resources.videoMute );
		_muteVolumeContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, mute );
		
		
		_contextMenu = new FvContextMenu( );
		_contextMenu.push( _muteVolumeContext );
		_contextMenu.push( _decVolumeContext );
		_contextMenu.push( _incVolumeContext );
		_contextMenu.push( _stopItemContext );
		_contextMenu.push( _playItemContext );
		_contextMenu.push( _fullItemContext );
	}
	
	private function _onContextAppendVolume( event : FvContextMenuEvent, value : Number ) : Void
	{
		appendVolume( value );	
	}
	
	private function _onDocumentLoaded( event : GraphicLibEvent ) : Void
	{
		super._onDocumentLoaded( event );
		
		onLocalisationUpdate();
		_videoMC.menu = _contextMenu.menu;
		
		_fireCompleteEvent();
	}
	
	private function _onDocumentError( event : IEvent ) : Void
	{
		_controller.release();
		
		super._onDocumentError( event );
	}
	
	private function _onPlayHeadChange( event : VideoDisplayEvent ) : Void
	{
		broadcastEvent( new FvReaderEvent( onVideoPlayHeadChangeEVENT, _getReader() ) );
	}
	
	private function _onMetaData( event : VideoDisplayEvent ) : Void
	{
		_controller.removeEventListener( FvVideoDisplay.onMetaDataEVENT, this );
		
		var meta : VideoMetaData = FvVideoDisplay( event.getTarget()).getMetaData();
		
		getDocument().setMetaData( meta );
		getDocument().setTitle( getDocument().getTitle() );
		
		_fireEventType( onMetaDataEVENT );
	}
	
	private function _onModeChanged( event : StageEvent ) : Void
	{
		if( _fullPlayer.isRunning() && !Fever.application.isFullScreen() )
		{
			var time : Number = _fullPlayer.getPlayHeadTime();
			_fullPlayer.close();
			
			Fever.application.removeEventListener( ApplicationEvent.onStateChangeEVENT, this );
			
			play( time );
			_fireEventType( onFullScreenEVENT );
		}
	}
	
	private function _onCloseAlertDialog() : Void
	{
		play();
	}
	
	private function _onCuePoint( event : VideoCuePointEvent ) : Void
	{
		broadcastEvent( new BubbleEvent( FvVideoDisplay.onCuePointEVENT, event.getCuePoint() ) );
	}
	
	private function _bubbleEvent( event : IEvent ) : Void
	{
		_fireEventType( event.getType() );
	}
}